//此js用来获取网页源码
var system = require('system');  //get args
var args = system.args;
if (args.length === 2) {
    var port = Number(args[1]);
}
else {
    var port = 9123;
}
var webserver = require('webserver');
var server = webserver.create()
//https://www.jianshu.com/p/15cba843bb55   server模块使用
var service = server.listen(port, function (request, response) {
    try {
        var jishu = 1;
        var postRaw = request.postRaw;
        var params = {};
        var val = '';
        var page_size = '';
        var post_raw = postRaw.split("&");
        if (post_raw.length > 1) {
            for (var i = 0; i < post_raw.length; i++) {
                val = post_raw[i].split("=");
                params[val[0]] = val[1];
            }
        } else {
            val = postRaw.split("=")
            params[val[0]] = val[1];
        }
        url = decodeURIComponent(params.url);
        page_size=params.page_size;
        // 创建page
        var webPage = require('webpage');
        var page = webPage.create();
        page.settings.resourceTimeout = 20000;//timeout is 20s
        page.loadImages = false;//不要加载图片
        ///////////////////////////////这个地方需要做成配置文件的方式，目前看cookie的有效期至少是一年
        phantom.addCookie({
            'name'     : 'SID',   /* required property */
            'value'    : 'cYBjo0pMdcLUJpcsBqhQoI9nYYj63QmYZjFw',  /* required property */
            'domain'   : '.ele.me',
            'path'     : '/',                /* required property */
            'httponly' : true,
            'secure'   : false,
            'expires'  : (new Date()).getTime() + (24 * 60 * 60 *365)
        });
        phantom.addCookie({
            'name'     : 'USERID',   /* required property */
            'value'    : '65869656',  /* required property */
            'domain'   : '.ele.me',
            'path'     : '/',                /* required property */
            'httponly' : true,
            'secure'   : false,
            'expires'  : (new Date()).getTime() + (24 * 60 * 60 *365)
        });
        phantom.addCookie({
            'name'     : '_utrace',   /* required property */
            'value'    : '66364bb3844b56644f8ff6f1e3c7adae_2018',  /* required property */
            'domain'   : '.ele.me',
            'path'     : '/',                /* required property */
            'httponly' : true,
            'secure'   : false,
            'expires'  : (new Date()).getTime() + (24 * 60 * 60 *365)
        });
        phantom.addCookie({
            'name'     : 'ubt_ssid',   /* required property */
            'value'    : '4anxwq1o2ho9jiw9i6psqa209be1opol_2018',  /* required property */
            'domain'   : '.ele.me',
            'path'     : '/',                /* required property */
            'httponly' : true,
            'secure'   : false,
            'expires'  : (new Date()).getTime() + (24 * 60 * 60 *365)
        });
        phantom.addCookie({
            'name'     : 'track_id',   /* required property */
            'value'    : '1518510634|f23495aebde56199e4a2cb7f7f2cdfb19e8fa8fe11bba0b662|5a21fb0e7fc86ba6be4645818f7382ab',  /* required property */
            'domain'   : '.ele.me',
            'path'     : '/',                /* required property */
            'httponly' : true,
            'secure'   : false,
            'expires'  : (new Date()).getTime() + (24 * 60 * 60 *365)
        });
        // 页面错误捕捉
        page.onError = function (msg, trace) {
            console.log("[Warning]This is page.onError");
            var msgStack = ['ERROR: ' + msg];
            if (trace && trace.length) {
                msgStack.push('TRACE:');
                trace.forEach(function (t) {
                    msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
                });
            }
            //console.error(msgStack.join('\n'));
        };
        // phantomjs错误捕捉
        phantom.onError = function (msg, trace) {
            console.log("[Warning]This is phantom.onError");
            var msgStack = ['PHANTOM ERROR: ' + msg];
            if (trace && trace.length) {
                msgStack.push('TRACE:');
                trace.forEach(function (t) {
                    msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function + ')' : ''));
                });
            }
            console.error(msgStack.join('\n'));
            phantom.exit(1);
        };
        // 打开网页，获取源码
        page.open(url, function (status) {
            console.log('Target_url is ' + url);  //输出待检测的网站url
            if(page>0){

            }
            if(page_size>0){
                window.setInterval(function () {
                    if (jishu < page_size) {
                        page.evaluate(function () {
                            // Scrolls to the bottom of page
                            window.document.body.scrollTop = document.body.scrollHeight;
                        });
                    }
                    jishu = jishu + 1;
                }, 1000); // Number of milliseconds to wait between scrolls
            }
            // 由于页面中的资源是动态加载的，需要setTimeout 10s 等待资源加载完，再操作页面。
            window.setTimeout(function () {
                if (status == 'success') {
                    var body = page.content;
                } else {
                    var body = "";
                }
                response.status = 200;
                response.write(body);  //返回获取到的网页源码
                //response.write(current_url); //返回当前的网页url
                page.close();
                response.close();
            }, 6000);

        });
    }
    catch (e) {
        console.log('[Error]' + e.message + 'happen' + e.lineNumber + 'line');
    }
});
//如果不设置浏览器宽度可能抓不到数据
server.viewportSize = {
    width: 1200,
    height: 3000
};